<?php
/**
 * 使用fsockopn() 创建一个websocket 连接
 * 但是无法直接通信,wesocket通信不能直接使用fwrite()
 * Sec-WebSocket-Key 是一个 Base64 编码的字符串，解码后必须是 16 字节的随机数据。
 */
$port = 9503;
$sock = fsockopen('127.0.0.1', $port, $errno, $errstr, 1);
$secKey = base64_encode(random_bytes(16));
if (!$sock) {
echo 'error: ' . $errstr . "<br/>\n";exit;
}
socket_set_blocking($sock, false);
$out = "";
$out .= "GET / HTTP/1.1\r\n";
$out .= "Host: 127.0.0.1:9502\r\n";
$out .= "Upgrade: websocket\r\n";
$out .= "Connection: Upgrade\r\n";
$out .= "Origin: http://127.0.0.1:9502\r\n";
$out .= "Sec-WebSocket-Key: $secKey\r\n";
$out .= "Sec-WebSocket-Version: 13\r\n\r\n";

fwrite($sock, $out);  #升级协议
//读取数据
while (!feof($sock)) {
    echo $response = fread($sock, 128) . "\n";
    if (strpos($response, '101 Switching Protocols') !== false) {
        echo "WebSocket 握手成功\n";
        break;
    }
}
fclose($sock);
